import random
from fire import Fire

class Room(object):
    #Static "rooms collapsed"
    roomsCollapsed = 0
    
    def __init__(self, levelfile):
        #Open and format file
        data = open(levelfile).readlines()
        data = [line.rstrip() for line in data]
        
        #Set Room Information
        self.name = data[0]
        self.maxFires = int(data[1])
        self.roomRects = data[2].split(';')
        
        for i, rectangle in enumerate(self.roomRects):
            self.roomRects[i] = rectangle.split(',')
            for j, coordinate in enumerate(self.roomRects[i]):
                self.roomRects[i][j] = float(coordinate)
            if len(self.roomRects[i]) != 4:
                print "Corrupted level file, improper rects: %s" % levelfile
                quit()
        
        self.zLevel = float(data[3])
        
        #Keeps track of time for room damage
        self.lastTime = 0
        
        #Determines item spawn location information
        itemSpawn = data[4]
        itemSpawn = itemSpawn.split(';')
        if itemSpawn[0] == 'y':
            self.itemsSpawn = True
        else:
            self.itemsSpawn = False
            
        self.spawnLocations = []
        
        if self.itemsSpawn == True:
            self.spawnLocations = itemSpawn[1:]
            for i, location in enumerate(self.spawnLocations):
                self.spawnLocations[i] = location.split(',')
                for coordinate in self.spawnLocations[i]:
                    coordinate = float(coordinate)
                if len(self.spawnLocations[i])!= 3:
                    print "Corrupted level file, improper item spawn locations: %s" % levelfile
                    quit()
         
        #Health Info
        if data[5] == 'Y':
            self.canBeDestroyed = True
        else:
            self.canBeDestroyed = False
            
        self.maxHealth = float(data[6])
        self.curHealth = self.maxHealth
        self.isDestroyed = False
        
        #List of room's fire data
        self.fireList = [self.maxFires]
        
        try:
            self.door_ids = data[7].split(';')
            print self.door_ids
            self.door_ids = [int(id) for id in self.door_ids]
        except:
            print "no door ids found for room %s" % self.name
            self.door_ids = []
            pass
            
        self.lastSpread = 0
            
        #Item information
        self.itemContained = None
        self.itemLocation = 0
        
        
    def spawnFireRandom(self):
        chosenrect = int(random.uniform(0,len(self.roomRects)))
        xpos = random.uniform(self.roomRects[chosenrect][0],self.roomRects[chosenrect][2])
        ypos = random.uniform(self.roomRects[chosenrect][1],self.roomRects[chosenrect][3])
    
        self.fireList.append(Fire(x = xpos, y = ypos, z = self.zLevel))
        
    def updateFires(self, task):
        """Updates the fires in the room"""
        #Update fires
        remove_list = []
        for i, fire in enumerate(self.fireList[1:]):
            if(self.fireList[i+1].isDone()):
                remove_list.append(self.fireList[i+1])
            else:
                self.fireList[i+1].update(self.fireList, task)
                if fire.spawnNeeded == True:
                    self.fireList[i + 1].spawnNeeded = False
                    self.spawnFireRandom()
                
        
        #remove done fires
        for a_fire in remove_list:
            del base.fire_dict[a_fire.fireGroundColNp]
            self.fireList.remove(a_fire)
            #print "removing fire"
            
        #Check if room is destroyed
        if self.isDestroyed == False:        
            elapsed = task.time - self.lastTime
            if(elapsed > 1.2):
                self.lastTime = task.time
                numfires = len(self.fireList) - 1
                self.curHealth -= numfires * .2
                if self.curHealth <= 0 and self.canBeDestroyed == True:
                    self.collapse()
        
    def collapse(self):
        """Collapses a room"""
        self.isDestroyed = True
        for i, f in enumerate(self.fireList[1:]):
            self.fireList[i + 1].cleanup()
        self.fireList = self.fireList[0:1]
        for an_id in self.door_ids:
            base.door_dict[an_id].roomCollapsed()
        print self.name + " has collapsed!"
        Room.roomsCollapsed += 1